#include "net.h"
#include "ui_net.h"

net::net(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::net)
{
    ui->setupUi(this);

    // switchbutton=new switchbuttom();
    // connect(switchbutton,&switchbuttom::clicked,this,&net::led_clicked);
    // // QLabel *ledpic=new QLabel();
    // //QPixmap Pixmap(":/images/led.jpg");
    // //Pixmap = Pixmap.scaled(100,100, Qt::KeepAspectRatio);
    // //ledpic->setPixmap(Pixmap);t
    // switchbutton->setFixedSize(100,35);
    my_timer =  new QTimer(this);
    connect(my_timer,SIGNAL(timeout()),this,SLOT(slot_timeout()));
    my_timer->start(1000);

    su03t=new QSerialPort();
    su03t->setPortName("/dev/ttymxc3");
    connect(su03t, SIGNAL(readyRead()), this,SLOT(su03treadPort()));
    su03t->setBaudRate(QSerialPort::Baud115200);
    //serial->setPort("/ttymxc2");
    su03t->setStopBits(QSerialPort::OneStop);
    su03t->setDataBits(QSerialPort::Data8);
    su03t->setFlowControl(QSerialPort::NoFlowControl);
    su03t->setParity(QSerialPort::NoParity);
    if (su03t->open(QIODevice::ReadWrite)) {
        // 获取已打开串口的名称
        QString portName = su03t->portName();
        qDebug() << "su-03t is open" << portName;
    } else {
        qDebug() << "su-03t open error";
    }

    serial=new QSerialPort();
    serial->setPortName("/dev/ttymxc2");
    connect(serial, SIGNAL(readyRead()), this,SLOT(readPort()));
    serial->setBaudRate(QSerialPort::Baud115200);
    //serial->setPort("/ttymxc2");
    serial->setStopBits(QSerialPort::OneStop);
    serial->setDataBits(QSerialPort::Data8);
    serial->setFlowControl(QSerialPort::NoFlowControl);
    serial->setParity(QSerialPort::NoParity);
    if (serial->open(QIODevice::ReadWrite)) {
        // 获取已打开串口的名称
        QString portName = serial->portName();
        qDebug() << "uart is open" << portName;
    } else {
        qDebug() << "uart open error";
    }
    //AT指令设置ap模式
    while(ESP8266_SendCmd("AT\r\n","OK\r\n"));
    while(ESP8266_SendCmd("AT+CWMODE=2\r\n","OK\r\n"));
    //ESP8266_SendCmd("AT+CIPAP?","OK\r\n");
    while(ESP8266_SendCmd("AT+CIPAP=\"192.168.4.1\",\"192.168.4.1\",\"255.255.255.0\"\r\n","OK\r\n"));
    //ESP8266_SendCmd("AT+CWSAP=\"ESP8266\",\"1234567890\",1,3\r\n","OK\r\n");
    //Sleep(3);
    //esp->serial->write("AT+CWSAP?");
    //esp->serial->write("AT+CWSAP=\"ESP8266\",\"1234567890\",1,3\r\n");
    while(ESP8266_SendCmd("AT+CWSAP=\"ESP8266\",\"1234567890\",1,3\r\n","OK\r\n"));
    while(ESP8266_SendCmd("AT+CIPMUX=1\r\n","OK\r\n"));
    while(ESP8266_SendCmd("AT+CIPSERVER=1,8080\r\n","OK\r\n"));
    //ESP8266_SendCmd("AT+CIFSR\r\n","OK\r\n");
    //AT+CIPAP=“192.168.5.1”,“192.168.5.1”,“255.255.255.0
    buffer.clear();
    flag=1;

    //连接onenet
    client=new QMqttClient();
    client->setHostname("mqtts.heclouds.com");
    client->setPort(1883);
    client->setClientId("device");//设备ID
    client->setUsername("a8Ifqm939M"); //产品ID
    //鉴权信息ID
    client->setPassword("version=2018-10-31&res=products%2Fa8Ifqm939M%2Fdevices%2Fdevice&et=1756953821&method=md5&sign=BLEVzs%2Bk0ksCvkyE%2FoCx2Q%3D%3D");
    connect(client,&QMqttClient::connected,this,&net::connectsucceed);
    connect(client,&QMqttClient::disconnected,this,&net::disconnectonenent);
    connect(client,&QMqttClient::messageReceived,this,&net::mqttreceive);
    client->connectToHost();

    layoutInit();
    // char abc[10];
    // abc[0]='55';
    connect(connectto,&QPushButton::clicked,this,&net::connectto_clicked);
}

net::~net()
{
    delete ui;
}


bool net::ESP8266_SendCmd(QByteArray str, QString res)
{
   serial->write(str);
    // if(esp->serial->waitForReadyRead(5000))
    // {
    Sleep(100);
   //QThread::msleep(50);
    //qDebug()<<(buffer);
    if(buffer.endsWith(res))
    {
        //buffer.clear();
        // qDebug()<<("succees");
        return 0;
    }else
    {
        qDebug()<<("error");
        return 1;
    }
    //}
}


void net::Sleep(int msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}


void net::readPort()
{
    QByteArray data =serial->readAll();
    if (data.isNull()) {
        qDebug()<<"empty";
        return;
    }

    buffer.append(data);
    qDebug()<<data;
    if(flag==1)
    {

        jsonreceive(data);
    }
}

void net::connectto_clicked()
{
    client->connectToHost();
    qDebug()<<"connect";
}
void net::disconnectonenent()
{
    QMessageBox::warning(this,"连接提示","连接断开");
    connectto->setEnabled(true);
    onenetstatus->setText("离线");
}

void net::jsonreceive(QByteArray data)
{

    QString str = data;
    int colonIndex = str.indexOf(':');  // 找到第一个冒号的位置
    if (colonIndex != -1) {
        res = str.mid(colonIndex + 1);
        qDebug()<<"result:"<<res;        // 获取冒号后的所有内容



    jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    if(!jsonDoc.isNull()&&jsonDoc.isObject())
    {
        jsonobj=jsonDoc.object();
        client->publish(topic,jsonDoc.toJson());
        json_status(jsonobj);
       // QJsonDocument jsdoc(jsonobj);

        qDebug()<<"jsonDoc:"<<jsonDoc.toJson();
        //onenetpublic();
        qDebug()<<"json success";
    }else
    {
        qDebug()<<"json error";
    }
    }
}

void net::json_status(QJsonObject jsonobj)
{
    if(jsonobj.contains("params")&&jsonobj["params"].isObject())
    {
        //qDebug()<<"params1111111111111111";
        QJsonObject params=jsonobj["params"].toObject();
         if(params.contains("temp")&&params["temp"].isObject())
        {
            //qDebug()<<"temp";
            QJsonObject temp=params["temp"].toObject();
            qDebug()<<"temp:"<<temp["value"];
            temptext->setText(QString::number(temp["value"].toDouble()));
            onenetdata.temp=temptext->text().toInt();
            qDebug()<<"tempvalue:"<<QString::number(temp["value"].toDouble());

         }
         if(params.contains("humility")&&params["humility"].isObject())
         {
             //qDebug()<<"temp";
             QJsonObject humility=params["humility"].toObject();
            humtext->setText(QString::number(humility["value"].toDouble()));
             onenetdata.humility=humtext->text().toInt();

         }
         if(params.contains("sun")&&params["sun"].isObject())
         {
            QJsonObject sun=params["sun"].toObject();
            suntext->setText(QString::number(sun["value"].toDouble()));
            onenetdata.sun=suntext->text().toInt();
         }


    }
}

void net::sundatasu03t()
{
    qDebug()<<onenetdata.sun;
    int num=onenetdata.sun;
    //int count = 0;
    if (num /256 >0) {
        sunsu03t[1]=num/256;
        //sunsu03t[0]=256-num/256;
        sunsu03t[0]=num%256;
    } else {
        sunsu03t[1]=0x00;
        sunsu03t[0]=num;
    }
}

// void net::onenetpublic()
// {
//     qDebug()<<"temp:"<<data->temp;
//     qDebug()<<"humility:"<<data->humility;
//     qDebug()<<"sun:"<<data->sun;
// }
void net::connectsucceed()
{
    QMessageBox::information(this,"连接提示","连接成功");
    connectto->setEnabled(false);
    onenetstatus->setText("在线");
    client->subscribe(subtopic);
}





const char LEDON[1]={'0'};
const char LEDOFF[1]={'1'};
void net::led_clicked(bool ledstatus)
{
    qDebug()<<"led clicked";
    QFile file;
    file.setFileName("/dev/dtsplatled");
    if(!file.open(QIODevice::WriteOnly))
    {
        qDebug()<<"error";

    }
    if(ledstatus==false)
    {
        file.write(LEDOFF);
    }else if(ledstatus==true)
    {
        file.write(LEDON);
    }
    file.close();

    QJsonObject obj;
    obj["id"]="123";
    QJsonObject params;
    QJsonObject led;
    led["value"]=ledstatus;
    params["led"]=led;
    obj["params"]=params;

    QJsonDocument jsonDoc(obj);
    client->publish(topic,jsonDoc.toJson());


}

void net::mqttreceive(const QByteArray &ba, const QMqttTopicName &topic)
{
    qDebug()<<ba;
   // QJsonArray data=ba;
    QJsonDocument doc=QJsonDocument::fromJson(ba);
    if(!doc.isNull()&&doc.isObject())
    {

        QJsonObject obj=doc.object();
        if(obj.contains("params")&&obj["params"].isObject())
        {
            qDebug()<<"111111111";
            QJsonObject params=obj["params"].toObject();
            switchbutton->Getswitchbtnvalue(params["led"].toBool());
            qDebug()<<params["led"];
        }

    }
}

void net::slot_timeout()
{
    timelabel->setText(QTime::currentTime().toString("hh:mm:ss"));
    datelabel->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd ddd"));
}

void net::su03treadPort()
{
    QByteArray data =su03t->readAll();
    if (data.isNull()) {
        qDebug()<<"empty";
        return;
    }
    qDebug()<<data;
    QString hexString = data.toHex(' ');
    qDebug()<<hexString;
    int i=hexString.toInt();
    qDebug()<<"suo3t data:"<<i;
    switch(i)
    {
    case 1:
        switchbutton->Getswitchbtnvalue(true);
        break;
    case 2:
        switchbutton->Getswitchbtnvalue(false);
        break;
    case 3:
        memset(msg,0,sizeof(msg));
        msg[0]=0xAA;
        msg[1]=0x55;
        msg[2]=0x01;
        msg[3]=onenetdata.temp;
        msg[4]=0x55;
        msg[5]=0xAA;
       // msg[3]=20;
        su03t->write(msg);
        break;
    case 4:
        memset(msg,0,sizeof(msg));
        msg[0]=0xAA;
        msg[1]=0x55;
        msg[2]=0x02;
        msg[3]=onenetdata.humility;
        msg[4]=0x55;
        msg[5]=0xAA;
        //msg[3]=50;
        su03t->write(msg);
        break;
    case 5:
        qDebug()<<"sun su03t";
        memset(msg,0,sizeof(msg));
        sundatasu03t();
        qDebug()<<sunsu03t[0]<<"-------------"<<sunsu03t[1];
       // char sg[10]={0xAA,0x55,0x03,0xE9,0x00,0x00,0x00,0x55,0xAA};
        msg[0]=0xAA;
        msg[1]=0x55;
        msg[2]=0x03;
        msg[3]=sunsu03t[0];
        msg[4]=sunsu03t[1];
        msg[5]=0x00;
        msg[6]=0x00;
        msg[7]=0x55;
        msg[8]=0xAA;
        qDebug()<<msg;
        su03t->write(msg,9);
        break;
    }
    // if(data==1)
    // {
    //     switchbutton->Getswitchbtnvalue(true);
    // }else if(data==2)
    // {
    //      switchbutton->Getswitchbtnvalue(true);
    // }
}

// void net::updateTime()
// {
//     ui->timelabel->setText(QTime::currentTime().toString("hh:mm"));
//     ui->timedate->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd ddd"));
// }

void net::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QStyleOption opt;
    opt.init(this);
    QPainter painter(this);
    style()->drawPrimitive(QStyle::PE_Widget,&opt,&painter,this);
}

void net::layoutInit()
{
    for (int i = 0; i < 9; i++) {
        widget[i] = new QWidget();
        widget[i]->setObjectName(tr("widget%1")
                                     .arg(QString::number(i)));
    }

    widget[0]->setMaximumHeight(100);
    widget[1]->setMaximumHeight(190);
   // widget[1]->setStyleSheet("border:1px solid red");
    widget[2]->setMaximumHeight(190);
    //widget[0]->setStyleSheet("border:1px solid red");
    //主布局
    vmainbox =new QVBoxLayout();
    vmainbox->addWidget(widget[0]);
    vmainbox->addWidget(widget[1]);
    vmainbox->addWidget(widget[2]);



    //显示云平台状态
    onenetstatus=new QLabel();
    onenetstatus->setObjectName("onenetstatus");
    connectto=new QPushButton();
    connectto->setFixedSize(100,35);
    //connectto->setStyleSheet("background-color:red");
    connectto->setObjectName("connectto");
    connectto->setText("连接云平台");
    QHBoxLayout*onenetBoxLayout=new QHBoxLayout();
    onenetBoxLayout->addWidget(connectto);
    onenetBoxLayout->addWidget(onenetstatus);
    widget[3]->setLayout(onenetBoxLayout);

    timelabel=new QLabel();
    timelabel->setObjectName("timelabel");
    timelabel->setText(QTime::currentTime().toString("hh:mm:ss"));
    datelabel=new QLabel();
    datelabel->setObjectName("datelabel");
    datelabel->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd ddd"));
    QVBoxLayout*vtimelayout=new QVBoxLayout();
    vtimelayout->addWidget(timelabel,2);
    vtimelayout->addWidget(datelabel,1);
    widget[4]->setLayout(vtimelayout);

    QHBoxLayout*widget0layout=new QHBoxLayout();
    widget0layout->addWidget(widget[3],1);
    widget0layout->addWidget(widget[4],2,Qt::AlignTop | Qt::AlignRight);
    widget[0]->setLayout(widget0layout);

    //温度图片
    QPixmap tempPixmap(":/images/temp.jpg");
    tempPixmap = tempPixmap.scaled(100,100, Qt::KeepAspectRatio);//缩放保持纵横比
    QLabel*templabel=new QLabel();
    templabel->setPixmap(tempPixmap);
    templabel->setFixedSize(100,100);
    //温度文字
    QLabel*tempIndex=new QLabel();
    tempIndex->setObjectName("tempIndex");
    tempIndex->setText("温度");
    tempIndex->setAlignment(Qt::AlignCenter);
    QVBoxLayout*vtemplayout=new QVBoxLayout();
    vtemplayout->addWidget(templabel);
    vtemplayout->addWidget(tempIndex);
    //温度数据
    temptext=new QLabel();
    temptext->setObjectName("temptext");
    temptext->setFixedSize(100,100);
    QHBoxLayout*tempLayout=new QHBoxLayout();
    tempLayout->addLayout(vtemplayout);
    tempLayout->addWidget(temptext);
    widget[5]->setLayout(tempLayout);


    //湿度图片
    QPixmap humPixmap(":/images/humilty.jpg");
    humPixmap = humPixmap.scaled(100,100, Qt::KeepAspectRatio);//缩放保持纵横比
    QLabel*humlabel=new QLabel();
    humlabel->setPixmap(humPixmap);
    humlabel->setFixedSize(100,100);
    //湿度文字
    QLabel*humIndex=new QLabel();
    humIndex->setObjectName("humIndex");
    humIndex->setText("湿度");
    humIndex->setAlignment(Qt::AlignCenter);
    QVBoxLayout*vhumlayout=new QVBoxLayout();
    vhumlayout->addWidget(humlabel);
    vhumlayout->addWidget(humIndex);
    //湿度数据
    humtext=new QLabel();
    humtext->setObjectName("humtext");
    humtext->setFixedSize(100,100);
    QHBoxLayout*humLayout=new QHBoxLayout();
    humLayout->addLayout(vhumlayout);
    humLayout->addWidget(humtext);
    widget[6]->setLayout(humLayout);

    QHBoxLayout*widget1layout=new QHBoxLayout();
    widget1layout->addWidget(widget[5],1,Qt::AlignLeft);
    widget1layout->addWidget(widget[6],1, Qt::AlignRight);
    widget1layout->setContentsMargins(40,0,40,0);
    widget[1]->setLayout(widget1layout);

    QPixmap sunPixmap(":/images/sun.jpg");
    sunPixmap = sunPixmap.scaled(100,100, Qt::KeepAspectRatio);//缩放保持纵横比
    QLabel*sunlabel=new QLabel();
    sunlabel->setPixmap(sunPixmap);
    sunlabel->setFixedSize(100,100);
    //光照文字
    QLabel*sunIndex=new QLabel();
    sunIndex->setObjectName("sunIndex");
    sunIndex->setFixedSize(100,100);
    sunIndex->setText("光照");
    sunIndex->setAlignment(Qt::AlignCenter);
    QVBoxLayout*vsunlayout=new QVBoxLayout();
    vsunlayout->addWidget(sunlabel);
    vsunlayout->addWidget(sunIndex);
    //温度数据
    suntext=new QLabel();
    suntext->setObjectName("suntext");
    suntext->setFixedSize(90,90);
    QHBoxLayout*sunLayout=new QHBoxLayout();
    sunLayout->addLayout(vsunlayout);
    sunLayout->addWidget(suntext);
    widget[7]->setLayout(sunLayout);
    widget[7]->setFixedWidth(225);
    //led
    QPixmap ledPixmap(":/images/led.jpg");
    ledPixmap = ledPixmap.scaled(100,100, Qt::KeepAspectRatio);//缩放保持纵横比
    QLabel*ledlabel=new QLabel();
    ledlabel->setPixmap(ledPixmap);
    ledlabel->setFixedSize(100,100);
    // //温度文字
    QLabel*ledIndex=new QLabel();
    ledIndex->setObjectName("ledIndex");
    ledIndex->setFixedSize(100,100);
    ledIndex->setText("灯光");
    ledIndex->setAlignment(Qt::AlignCenter);
    QVBoxLayout*vledlayout=new QVBoxLayout();
    vledlayout->addWidget(ledlabel);
    vledlayout->addWidget(ledIndex);
    // //开关
    switchbutton=new switchbuttom();
    switchbutton->setFixedSize(100,35);
    connect(switchbutton,&switchbuttom::clicked,this,&net::led_clicked);
    QHBoxLayout*ledLayout=new QHBoxLayout();
    ledLayout->addLayout(vledlayout);
    ledLayout->addWidget(switchbutton);
    widget[8]->setLayout(ledLayout);

    QHBoxLayout*widget2layout=new QHBoxLayout();
    widget2layout->addWidget(widget[7],1,Qt::AlignLeft);
    widget2layout->addWidget(widget[8],1,Qt::AlignRight);
    widget2layout->setContentsMargins(40,0,40,0);
    widget[2]->setLayout(widget2layout);


    temptext->setText(QString::number(20));
    this->setLayout(vmainbox);

}


onenectdata::onenectdata(QWidget *parent)
{

}
